package conf

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"io/ioutil"
	"os"
)

const (
	ErrOk            = 0
	ErrNotLogined    = -10001
	ErrDeviceHasBind = -10002
	ErrIllegalOrInvalid = -10003
	ErrShareDeviceHasBind = -10004
	ErrShareDeviceNotBind = -10005
	ErrDeviceNotExist	  = -10006
	ErrIsAdmin			  = -10007
	ErrGeneral			  = -10008
)

type appConfig struct {
	DbUrl             string
	EmqAuthDbUrl      string
	MqttHost          string
	MqttPort          int
	MqttUseSsl        bool
	MqttAdminUser     string
	MqttAdminPassword string
	TestGatewayIds    []string
	MqttFactoryKey    string
	JwtToken          string
	PagesHost         string
	BasePrefix        string
}

var AppConfig = func() *appConfig {
	mqttPort, err := beego.AppConfig.Int("MqttPort")
	if err != nil {
		panic(err)
	}
	mqttUseSsl, err := beego.AppConfig.Bool("MqttUseSsl")
	if err != nil {
		panic(err)
	}
	ret := &appConfig{
		EmqAuthDbUrl:      beego.AppConfig.String("emqAuthDbUrl"),
		DbUrl:             beego.AppConfig.String("dbUrl"),
		MqttHost:          beego.AppConfig.String("MqttHost"),
		MqttPort:          mqttPort,
		MqttUseSsl:        mqttUseSsl,
		MqttAdminUser:     beego.AppConfig.String("MqttAdminUser"),
		MqttAdminPassword: beego.AppConfig.String("MqttAdminPassword"),
		TestGatewayIds:    beego.AppConfig.Strings("testGateways"),
		MqttFactoryKey:    beego.AppConfig.String("MqttFactoryKey"),
		JwtToken:          beego.AppConfig.String("JwtToken"),
		PagesHost:         beego.AppConfig.String("PagesHost"),
		BasePrefix:        beego.AppConfig.String("basePrefix"),
	}
	return ret
}()

type WxCfg struct {
	AppSecret           string
	AccessTokenReqtUrl  string
	AccessTokenJsonPath string
	JssdkTicketReqUrl   string
	JssdkTicketJsonPath string
}
type wxCfgManager struct {
	cfg map[string]*WxCfg
}

func (self *wxCfgManager) GetAppSecret(appId string) string {
	if account, ok := self.cfg[appId]; ok {
		return account.AppSecret
	} else {
		return ""
	}
}

func (self *wxCfgManager) GetAll() map[string]*WxCfg {
	return self.cfg
}

var WxCfgManager = func() *wxCfgManager {
	var wxCfgs map[string]*WxCfg
	fd, err := os.Open("./conf/mpConfig.json")
	if err != nil {
		panic(err)
	}
	defer fd.Close()
	content, err := ioutil.ReadAll(fd)
	if err != nil {
		panic(err)
	}
	err = json.Unmarshal(content, &wxCfgs)
	if err != nil {
		panic(err)
	}
	return &wxCfgManager{cfg: wxCfgs}
}()
